import React, { useState } from 'react';
import { useAppDispatch } from '../store';

import { todoAddAction } from '../store/action/todo';

export default function Header() {
  const dispatch = useAppDispatch();
  const [task, setTask] = useState('');

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      dispatch(todoAddAction(task));
      // 4.5 新增后清空输入框的内容
      setTask('');
    }
  };

  return (
    <header className="header">
      <h1>todos</h1>
      <input
        // 5.1 state控制value或checked
        value={task}
        className="new-todo"
        placeholder="需要做什么"
        autoFocus
        // 5.2 onChange配setState
        onChange={(e) => setTask(e.target.value)}
        // 6.3 监听键盘事件，回车事件时触发新增方法
        onKeyDown={handleKeyDown}
      />
    </header>
  );
}
